<template>
  <div class="set">
    <div class="set_ct">
      <Form ref="formValidate" v-show='loaded'
            :model="formData"
            :rules="ruleValidate"
            :label-width="120"
            class="set_ct_form">
             <FormItem label="配置开关：">
          <i-switch  size="large" v-model='switchStatus'>
            <span slot="open">开启</span>
            <span slot="close">关闭</span>
          </i-switch>
        </FormItem>
        <FormItem label="游戏币单价设置:" v-show='switchStatus'
                  prop="price">
          <!-- <Input v-model="formData.price"
                 @on-keyup='keyup'
                 style="width:280px;"
                 type="text">
          </Input> -->
          <Input v-model="formData.price"
                 :maxlength="7"
                 @on-blur="priceBlur"
                 @on-keyup="changeprice"
                 placeholder="可输入范围为0.00到9999.99之间"
                 style="width:280px;"></Input>
          <span style="padding-left:8px;">元</span>
        </FormItem>
        <FormItem>
          <Button type="primary"
                  class="btn"
                  @click="handleSubmit">确认</Button>
          <Button class="btn"
                  style="margin-left:20px;"
                  @click="cancel">取消</Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script>
import { getDicQuery, setDicSave } from '@/api/setting'
// import { routeEqual } from '@/libs/util'
import './index.less'
export default {
  data () {
    return {
      loaded: false,
      switchStatus: true,
      title: '游戏币单价设置',
      formData: {
        price: '1.00'
      },
      ruleValidate: {
        price: [{ required: true, type: 'string', message: '游戏币单价不能为空', trigger: 'blur' }, { required: true, message: '可输入范围为0.00到9999.99之间', trigger: 'blur', pattern: /^\d{1,4}(\.\d{1,2})?$/ }]
      }
    }
  },
  methods: {
    changeprice () {
      this.changeNum()
    },
    priceBlur () {
      this.formData.price = this.formData.price + ''
      // this.formData.price = this.formData.price.
      this.formData.price = this.formData.price.replace(/[^\d.]/g, '')
      if (this.formData.price === '') {
        this.formData.price = ''
      } else if (this.formData.price.indexOf('.') === -1) {
        this.formData.price = this.formData.price + '.00'
      } else if (this.formData.price.indexOf('.')) {
        let ste = this.formData.price.substring(this.formData.price.indexOf('.') + 1)
        if (!ste) {
          this.formData.price = this.formData.price + '00'
        }
        if (ste.length === 1) {
          this.formData.price = this.formData.price + '0'
        } if (ste.length > 2) {
          this.formData.price = this.formData.price.substring(0, this.formData.price.indexOf('.') + 3)
        }
      }
    },
    changeNum () {
      // 如果用户第一位输入的是小数点，则重置输入框内容
      if (this.formData.price !== '' && this.formData.price.substring(0, 1) === '.') {
        this.formData.price = ''
      }
      this.formData.price = this.formData.price.replace(/^0*(0\.|[1-9])/, '$1') // 粘贴不生效
      this.formData.price = this.formData.price.replace(/[^\d.]/g, '')
      this.formData.price = this.formData.price.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      this.formData.price = this.formData.price.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      this.formData.price = this.formData.price.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      if (this.formData.price.indexOf('.') < 0 && this.formData.price !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (this.formData.price.substring(0, 1) === '0' && this.formData.price.length === 2) {
          this.formData.price = this.formData.price.substring(1, this.formData.price.length)
        }
      }
      if (this.formData.price > 9999.99) {
        this.formData.price = this.formData.price.substring(0, 4)
      }
    },
    submitForm () {
      getDicQuery({
        shopId: this.$route.query.id,
        'dictKeys': 'pricePerCoin,pricePerCoinSwitch',
        'msType': '1',
        'merchantId': this.$store.state.user.merchantId
      }).then((res) => {
        this.loaded = true
        if (res.data.status === 200) {
          if (res.data.data[0].pricePerCoin === '0' || res.data.data[0].pricePerCoin === 0) {
            this.formData.price = '1.00'
          } else {
            this.formData.price = String(res.data.data[0].pricePerCoin)
          }
          if (res.data.data[1].pricePerCoinSwitch === '0' || res.data.data[1].pricePerCoinSwitch === 0) {
            this.switchStatus = false
          } else {
            this.switchStatus = true
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    closeModal () {
      this.$store.commit('closeTag', this.$route)
      // this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      // console.log(this.$store.state.app.tagNavList)
      // console.log(this.$store.state.app.tagNavList.length)
      if (this.$store.state.app.tagNavList[this.$store.state.app.tagNavList.length - 1].name !== 'store_setting') {
        this.$nextTick(() => {
          this.$router.push({
            name: 'store_setting', params: { id: this.$route.query.id }
          })
        })
      }
    },
    cancel () {
      this.closeModal()
      // this.formData.price = null
    },
    handleSubmit () {
      this.$refs.formValidate.validate((val) => {
        if (val) {
          setDicSave({
            shopId: this.$route.query.id,
            'pricePerCoin': this.formData.price + '',
            'pricePerCoinSwitch': this.switchStatus ? '1' : '0',
            'merchantId': this.$store.state.user.merchantId,
            'msType': '1'
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('设置成功')
              this.closeModal()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    }
  },
  mounted () {
    this.submitForm()
    if (!this.hasPermission('moms:setting:coinprice')) {
      this.$router.replace({ name: 'error_401' })
    }
  }
}
</script>
